import { Injectable, Logger } from '@nestjs/common'
import { JwtService } from '@nestjs/jwt'
import { threadId } from 'node:worker_threads'
import { IResponse } from 'src/interface/response.interface'
import { User } from 'src/interface/user.interface'
import { UserService } from 'src/module/user/user.service'
import { encript } from 'src/util/encription'
import * as svgCaptcha from 'svg-captcha'

const logger = new Logger('auth.service')

@Injectable()
export class AuthService {
    private response: IResponse
    private pointer: number = 0
    private captchas = {} // 验证码暂时先存放在这里
    constructor(
        private readonly userService: UserService,
        private readonly jwtService: JwtService,
    ) { }

    private async validateUser(user: User) {
        const phone: string = user.phone
        const password: string = user.password
        return await this.userService.findOneByPhone(phone)
            .then(res => {
                if (res.length === 0) {
                    this.response = { code: 3, msg: '用户尚未注册' }
                    throw this.response
                }
                return res[0]
            })
            .then((dbUser: User) => {
                const pass = encript(password, dbUser.salt)
                if (pass === dbUser.password) {
                    return this.response = { code: 0, msg: { userid: dbUser._id } }
                } else {
                    this.response = { code: 4, msg: '用户名或密码错误' }
                    throw this.response
                }
            })
            .catch(err => {
                return err
            })
    }

    async createToken(user: User) {
        return this.jwtService.sign(user)
    }

    async login(user: User) {
        // return await this.validateUser(user).then(() => { return this.createToken(user) })
        return await this.validateUser(user)
            .then(async (res: IResponse) => {
                if (res.code !== 0) {
                    this.response = res
                    throw this.response
                }
                const userid = res.msg.userid
                this.response = {
                    code: 0,
                    msg: {
                        token: await this.createToken(user),
                        userid
                    }
                }
                return this.response
            })
            .catch(err => err)
    }

    async createCaptcha(id?: string) {
        if (id) {
            delete this.captchas[id]
        }
        console.log(this.captchas)
        const c = svgCaptcha.create()
        this.captchas[this.pointer] = c.text
        this.response = {
            code: 0,
            msg: {
                id: this.pointer++,
                img: c.data
            },
        }
        return this.response
    }

    verification(code: string, id: string): boolean {
        return this.captchas[id] === code
    }
}
